package org.aynu.productservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.aynu.productservice.common.ProductResponse;
import org.aynu.productservice.entity.ProductCategoriesEntity;
import org.aynu.productservice.entity.ProductCategoryMappingEntity;
import org.aynu.productservice.entity.ProductEntity;
import org.aynu.productservice.mapper.ProductCategoriesMapper;
import org.aynu.productservice.mapper.ProductCategoryMappingMapper;
import org.aynu.productservice.mapper.ProductMapper;
import org.aynu.productservice.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.aynu.productservice.common.ProductStatusCode.*;

/**
 * 产品服务实装
 *
 * @author 小粥
 * @since 2025/03/03
 */

@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductEntity> implements ProductService {
    private final ProductMapper productMapper;
    private final ProductCategoriesMapper productCategoriesMapper;
    private final ProductCategoryMappingMapper productCategoryMappingMapper;


    @Autowired
    public ProductServiceImpl(ProductMapper productMapper, ProductCategoriesMapper productCategoriesMapper, ProductCategoryMappingMapper productCategoryMappingMapper) {
        this.productMapper = productMapper;
        this.productCategoriesMapper = productCategoriesMapper;
        this.productCategoryMappingMapper = productCategoryMappingMapper;
    }

    /**
     * 选择产品
     *
     * @return {@link ProductResponse }<{@link List }<{@link ProductEntity }>>
     * @author 小粥
     * @since 2025/03/03
     */// 获取所有商品
    @Override
    public ProductResponse<List<ProductEntity>> selectProduct() {
        try {
            LambdaQueryWrapper<ProductEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductEntity::getIsDeleted, 0); // 只查询未删除的商品
            List<ProductEntity> products = productMapper.selectList(queryWrapper);
            if (products == null || products.isEmpty()) {
                return ProductResponse.error(PRODUCT_INFO_RETRIEVE_FAILED);
            }
            return ProductResponse.success(PRODUCT_INFO_RETRIEVED, products);
        } catch (Exception e) {
            log.error("获取商品信息时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 按 ID 选择产品
     *
     * @param productId 产品 ID
     * @return {@link ProductResponse }<{@link ProductEntity }>
     * @author 小粥
     * @since 2025/03/03
     */// 通过商品 ID 查看商品详情
    @Override
    public ProductResponse<ProductEntity> selectProductById(int productId) {
        try {
            LambdaQueryWrapper<ProductEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductEntity::getProductId, productId)
                    .eq(ProductEntity::getIsDeleted, 0); // 只查询未删除的商品
            ProductEntity product = productMapper.selectOne(queryWrapper);
            if (product == null) {
                return ProductResponse.error(PRODUCT_INFO_RETRIEVE_FAILED);
            }
            return ProductResponse.success(PRODUCT_INFO_RETRIEVED, product);
        } catch (Exception e) {
            log.error("获取商品信息时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 创建产品类别
     *
     * @param productCategoriesEntity 产品类别实体
     * @return {@link ProductResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 创建商品分类
    @Override
    public ProductResponse<Integer> createProductCategory(ProductCategoriesEntity productCategoriesEntity) {
        try {
            // 设置默认值
            if (productCategoriesEntity.getIsDeleted() == 0) {
                productCategoriesEntity.setIsDeleted(0);
            }
            boolean result = productCategoriesMapper.insert(productCategoriesEntity) > 0;
            if (!result) {
                return ProductResponse.error(PRODUCT_CATEGORY_CREATE_FAILED);
            }
            return ProductResponse.success(PRODUCT_CATEGORY_CREATED, productCategoriesEntity.getCategoryId());
        } catch (Exception e) {
            log.error("创建商品分类时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 更新产品类别
     *
     * @param productCategoriesEntity 产品类别实体
     * @return {@link ProductResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 更新商品分类
    @Override
    public ProductResponse<Integer> updateProductCategory(ProductCategoriesEntity productCategoriesEntity) {
        try {
            LambdaUpdateWrapper<ProductCategoriesEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProductCategoriesEntity::getCategoryId, productCategoriesEntity.getCategoryId())
                    .set(ProductCategoriesEntity::getName, productCategoriesEntity.getName())
                    .set(ProductCategoriesEntity::getDescription, productCategoriesEntity.getDescription())
                    .set(ProductCategoriesEntity::getUpdatedAt, productCategoriesEntity.getUpdatedAt());
            boolean result = productCategoriesMapper.update(null, updateWrapper) > 0;
            if (!result) {
                return ProductResponse.error(PRODUCT_CATEGORY_UPDATE_FAILED);
            }
            return ProductResponse.success(PRODUCT_CATEGORY_UPDATED, productCategoriesEntity.getCategoryId());
        } catch (Exception e) {
            log.error("更新商品分类时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 删除产品类别
     *
     * @param categoryId 类别 ID
     * @return {@link ProductResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 逻辑删除商品分类
    @Override
    public ProductResponse<Integer> deleteProductCategory(int categoryId) {
        try {
            LambdaUpdateWrapper<ProductCategoriesEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProductCategoriesEntity::getCategoryId, categoryId)
                    .set(ProductCategoriesEntity::getIsDeleted, 1);
            boolean result = productCategoriesMapper.update(null, updateWrapper) > 0;
            if (!result) {
                return ProductResponse.error(PRODUCT_CATEGORY_DELETE_FAILED);
            }
            return ProductResponse.success(PRODUCT_CATEGORY_DELETED, categoryId);
        } catch (Exception e) {
            log.error("逻辑删除商品分类时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 选择产品类别
     *
     * @return {@link ProductResponse }<{@link List }<{@link ProductCategoriesEntity }>>
     * @author 小粥
     * @since 2025/03/03
     */// 获取商品分类表
    @Override
    public ProductResponse<List<ProductCategoriesEntity>> selectProductCategories() {
        try {
            LambdaQueryWrapper<ProductCategoriesEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductCategoriesEntity::getIsDeleted, 0); // 只查询未删除的分类
            List<ProductCategoriesEntity> productCategories = productCategoriesMapper.selectList(queryWrapper);
            if (productCategories == null || productCategories.isEmpty()) {
                return ProductResponse.error(PRODUCT_CATEGORY_RETRIEVE_FAILED);
            }
            return ProductResponse.success(PRODUCT_CATEGORY_RETRIEVED, productCategories);
        } catch (Exception e) {
            log.error("获取商品分类信息时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 创建产品
     *
     * @param productEntity product 实体
     * @param categoryId    类别 ID
     * @return {@link ProductResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 创建商品
    @Override
    public ProductResponse<Integer> createProduct(ProductEntity productEntity, int categoryId) {
        try {
            // 设置默认值
            if (productEntity.getIsDeleted() == 0) {
                productEntity.setIsDeleted(0);
            }
            // 创建商品
            boolean result1 = productMapper.insert(productEntity) > 0;
            if (!result1) {
                return ProductResponse.error(CREATE_PRODUCT_FAILED);
            }

            // 创建商品分类映射
            ProductCategoryMappingEntity mappingEntity = new ProductCategoryMappingEntity();
            mappingEntity.setProductId(productEntity.getProductId());
            mappingEntity.setCategoryId(categoryId);
            boolean result2 = productCategoryMappingMapper.insert(mappingEntity) > 0;
            if (!result2) {
                return ProductResponse.error(CREATE_PRODUCT_FAILED);
            }

            return ProductResponse.success(CREATE_PRODUCT, productEntity.getProductId());
        } catch (Exception e) {
            log.error("创建商品时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 删除产品
     *
     * @param productId 产品 ID
     * @return {@link ProductResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 逻辑删除商品
    @Override
    public ProductResponse<Integer> deleteProduct(int productId) {
        try {
            // 逻辑删除商品
            LambdaUpdateWrapper<ProductEntity> productUpdateWrapper = new LambdaUpdateWrapper<>();
            productUpdateWrapper.eq(ProductEntity::getProductId, productId)
                    .set(ProductEntity::getIsDeleted, 1);
            boolean result1 = productMapper.update(null, productUpdateWrapper) > 0;
            if (!result1) {
                return ProductResponse.error(PRODUCT_DELETE_FAILED);
            }

            // 删除商品分类映射
            LambdaUpdateWrapper<ProductCategoryMappingEntity> mappingUpdateWrapper = new LambdaUpdateWrapper<>();
            mappingUpdateWrapper.eq(ProductCategoryMappingEntity::getProductId, productId);
            boolean result2 = productCategoryMappingMapper.delete(mappingUpdateWrapper) >= 0;
            if (!result2) {
                return ProductResponse.error(PRODUCT_DELETE_FAILED);
            }

            return ProductResponse.success(PRODUCT_DELETED, productId);
        } catch (Exception e) {
            log.error("逻辑删除商品时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 更新产品
     *
     * @param productEntity product 实体
     * @return {@link ProductResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 更新商品信息
    @Override
    public ProductResponse<Integer> updateProduct(ProductEntity productEntity) {
        try {
            LambdaUpdateWrapper<ProductEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProductEntity::getProductId, productEntity.getProductId())
                    .set(ProductEntity::getName, productEntity.getName())
                    .set(ProductEntity::getDescription, productEntity.getDescription())
                    .set(ProductEntity::getPrice, productEntity.getPrice())
                    .set(ProductEntity::getStockQuantity, productEntity.getStockQuantity())
                    .set(ProductEntity::getImageUrl, productEntity.getImageUrl())
                    .set(ProductEntity::getUpdatedAt, productEntity.getUpdatedAt());
            boolean result = productMapper.update(null, updateWrapper) > 0;
            if (!result) {
                return ProductResponse.error(PRODUCT_INFO_UPDATE_FAILED);
            }
            return ProductResponse.success(PRODUCT_INFO_UPDATE_SUCCESS, productEntity.getProductId());
        } catch (Exception e) {
            log.error("更新商品信息时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 获取产品库存
     *
     * @param productId 产品 ID
     * @return {@link ProductResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 获取商品库存
    @Override
    public ProductResponse<Integer> getProductStock(int productId) {
        try {
            LambdaQueryWrapper<ProductEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductEntity::getProductId, productId)
                    .eq(ProductEntity::getIsDeleted, 0);
            ProductEntity product = productMapper.selectOne(queryWrapper);
            if (product == null) {
                return ProductResponse.error(PRODUCT_STOCK_RETRIEVE_FAILED);
            }
            return ProductResponse.success(PRODUCT_STOCK_RETRIEVED, product.getStockQuantity());
        } catch (Exception e) {
            log.error("获取商品库存时出现异常", e);
            return ProductResponse.error(e);
        }
    }

    /**
     * 更新产品库存
     *
     * @param productId 产品 ID
     * @param quantity  数量
     * @return {@link ProductResponse }<{@link Integer }>
     * @author 小粥
     * @since 2025/03/03
     */// 更新商品库存
    @Override
    public ProductResponse<Integer> updateProductStock(int productId, int quantity) {
        try {
            LambdaQueryWrapper<ProductEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductEntity::getProductId, productId)
                    .eq(ProductEntity::getIsDeleted, 0);
            ProductEntity product = productMapper.selectOne(queryWrapper);
            if (product == null) {
                return ProductResponse.error(PRODUCT_STOCK_RETRIEVE_FAILED);
            }

            int currentStock = product.getStockQuantity();
            int newStock = currentStock + quantity; // quantity 为正加，负减
            if (newStock < 0) {
                return ProductResponse.error("库存不足，无法减少到负值: productId=" , productId);
            }

            LambdaUpdateWrapper<ProductEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProductEntity::getProductId, productId)
                    .set(ProductEntity::getStockQuantity, newStock);
            boolean result = productMapper.update(null, updateWrapper) > 0;
            if (!result) {
                return ProductResponse.error(PRODUCT_STOCK_UPDATE_FAILED);
            }
            return ProductResponse.success(PRODUCT_STOCK_UPDATED, productId);
        } catch (Exception e) {
            log.error("更新商品库存时出现异常", e);
            return ProductResponse.error(e);
        }
    }

   @Override
public ProductResponse<List<ProductEntity>> selectProductByCategoryId(int categoryId) {
    try {
        // Step 1: 查询商品分类映射表，获取与 categoryId 关联的商品 ID 列表
        LambdaQueryWrapper<ProductCategoryMappingEntity> mappingQueryWrapper = new LambdaQueryWrapper<>();
        mappingQueryWrapper.eq(ProductCategoryMappingEntity::getCategoryId, categoryId);
        List<ProductCategoryMappingEntity> mappings = productCategoryMappingMapper.selectList(mappingQueryWrapper);

        if (mappings == null || mappings.isEmpty()) {
            return ProductResponse.error(PRODUCT_CATEGORY_MAPPING_NOT_FOUND);
        }

        // 提取商品 ID 列表
        List<Integer> productIds = mappings.stream()
                .map(ProductCategoryMappingEntity::getProductId)
                .toList();

        // Step 2: 根据商品 ID 列表查询商品信息
        LambdaQueryWrapper<ProductEntity> productQueryWrapper = new LambdaQueryWrapper<>();
        productQueryWrapper.in(ProductEntity::getProductId, productIds)
                .eq(ProductEntity::getIsDeleted, 0); // 只查询未删除的商品
        List<ProductEntity> products = productMapper.selectList(productQueryWrapper);

        if (products == null || products.isEmpty()) {
            return ProductResponse.error(PRODUCT_INFO_RETRIEVE_FAILED);
        }

        // Step 3: 返回查询结果
        return ProductResponse.success(PRODUCT_INFO_RETRIEVED, products);
    } catch (Exception e) {
        log.error("通过商品分类 ID 查询商品时出现异常", e);
        return ProductResponse.error(e);
    }
}

}